package cc.ttiot.thread.dataCollectionThread;

import cc.ttiot.mapper.dao.VibrationMsgMapper;
import cc.ttiot.mapper.dao.WindPressureMsgMapper;
import cc.ttiot.mapper.domain.VibrationMsg;
import cc.ttiot.mapper.domain.WindPressureMsg;
import cc.ttiot.mapper.utils.MybatisUtils;
import cc.ttiot.service.dataCollection.i2c.impl.VibrationCollection;
import cc.ttiot.service.dataCollection.i2c.impl.WindPressureCollection;
import cc.ttiot.utils.TimeUtils;
import com.pi4j.io.i2c.I2CDevice;
import org.apache.ibatis.session.SqlSession;

import java.io.IOException;

/**
 * @Description:
 * @Author :
 * @Version :
 * @Date :
 */
public class WindPressureCollectThread implements Runnable {
    //数据库初始化
    /*
        1) SqlSession类是线程不安全的，所以每个线程都要有个单独的SqlSession
        2) 下面这种sqlSessionFactory.openSession()的方式获取SqlSession对象默认事务autoCommit设为false，
           所以除了查询语句其他语句执行后要调用sqlSession.commit()方法提交事务
     */
    private final SqlSession sqlSession = MybatisUtils.getSqlSession();
    private final WindPressureMsgMapper wpmMapper = sqlSession.getMapper(WindPressureMsgMapper.class);
    private final WindPressureMsg windPressureMsg = new WindPressureMsg();

    private final I2CDevice device;

    public WindPressureCollectThread(I2CDevice device) {
        this.device = device;
    }

    @Override
    public void run() {
        WindPressureCollection windPressureCollection = WindPressureCollection.getInstance();
        windPressureCollection.setI2CDevice(device);
        while(true){
            synchronized (device) {
                try {
                    double windPressure = windPressureCollection.collect();
//                    System.out.printf("风压 = %.2f Pa\n",windPressure);

                    if(windPressure <= -5 || windPressure >= 5){
                        //更新数据
                        windPressureMsg.setWindPressure(windPressure);
                        windPressureMsg.setTime(TimeUtils.getMillisecondTime());

                        //存入数据库
                        wpmMapper.insertSingle(windPressureMsg);
                        sqlSession.commit();
                    }

                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
//            try {
//                Thread.sleep(500);
//            } catch (InterruptedException e) {
//                e.printStackTrace();
//            }
        }
    }

}
